/**
 * Created by chengming on 18/5/24.
 * version 1.0
 * 人民网
 */
const ArticleHrefAdapter = require('../ArticleHrefAdapter');
const request = require('request-promise');
const vm = require('vm');
const cheerio = require('cheerio');
const urlTool = require('url');
const logger = require('../../conf/logger');

module.exports = class Cfda extends ArticleHrefAdapter{

	initWinEnv(){
		global.window = {
			innerWidth:1232,
			innerHeight:632,
			screenX:11,
			screenY:22,
			screen:{
				width:1280,
				height:800
			}
		};

		global.document = {
			documentElement:{
				clientWidth:1217,
				clientHeight:550
			},
			body:{
				clientWidth:1217,
				clientHeight:1467
			},
			_cookie: [],

			get cookie(){
				return this._cookie;
			},

			set cookie(val){
				this._cookie.push(val);
			}
		};
	}

	async doRequest(){

		//初始化窗口属性
		this.initWinEnv();

		//创建全局cookie
		var jar = request.jar();
		
		//使用cookie
		const jsbody = await request({
			jar:jar,
			url: this.requestUrl,
			headers:{
				'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36',
			}
		});

        let js = await request({url:"http://cnda.cfda.gov.cn/4QbVtADbnLVIc/c.FxJzG50F.js?D9PVtGL=9a1adc"});
		let $ = cheerio.load(jsbody);

		let allJsContent = js;

		$('script').each(function () {
            let src = $(this).attr("src");
            if(!src){
                let s = $(this).html().trim();
				allJsContent += ` ${s}`;
            }
        });

		allJsContent = allJsContent.replace(/debugger/g, '');

        let vmData = vm.runInThisContext(allJsContent);

        console.log(vmData);

		/*
		let newUrl = urlTool.resolve(this.requestUrl, window.location);

		for(let cookieStr of document.cookie){
			let cookie = request.cookie(cookieStr);
			jar.setCookie(cookie, this.requestUrl);
		}
		*/

		return await request({
			jar:jar,
			url:newUrl,
			headers:{
				'Referer':this.requestUrl,
				'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36',
			},
			encoding:null
		});
	}
}